package org.example.chat.service.impl;

import cn.hutool.json.JSONUtil;
import org.example.chat.api.Constant;
import org.example.chat.dao.GroupRepository;
import org.example.chat.entity.Group;
import org.example.chat.service.IGroupService;
import org.example.chat.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GroupServiceImpl extends BaseService implements IGroupService {

    @Autowired
    private GroupRepository groupRepository;

    @Override
    public List<Group> getUserGroupsById(String userId) {
        String key = Constant.USER_GROUP_KEY_PREFIX + userId;
        String jsonStr = redisTemplate.opsForValue().get(key);
        List<Group> groups = null;
        if (jsonStr == null) {
            // 从数据库中获取，并缓存
            groups = groupRepository.findGroupByUserId(userId);
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(groups));
        } else {
            groups = JSONUtil.toList(jsonStr, Group.class);
        }
        return groups;
    }
}
